import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/userStore'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/info'
    },
    {
      path: '/info',
      name: 'info',
      component: () => import('@/components/InfoPublish.vue')
    },
    {
      path: '/chat',
      name: 'chat',
      component: () => import('@/components/chat.vue')
    },
    {
      path: '/resource',
      name: 'resource',
      component: () => import('@/components/ResourceShare.vue')
    },
    {
      path: '/forum',
      name: 'forum',
      component: () => import('@/components/Forum.vue')
    },
    {
      path: '/login',
      component: () => import('@/components/Login.vue')
    },
    {
      path: '/register',
      component: () => import('@/components/Register.vue')
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('@/components/UserProfile.vue')
    }
  ]
})

// 添加全局前置守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();
  const publicPages = ['/login', '/register'];

  if (!userStore.isLoggedIn) {
    await userStore.checkLogin(); // 添加await等待验证完成
  }

  if (!publicPages.includes(to.path) && !userStore.isLoggedIn) {
    next({ 
      path: '/login',
      query: { redirect: to.fullPath }
    });
  } else {
    next();
  }
});

export default router